package com.example.encrypt_demo.util;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;

/**
 * @author benjamin_5
 * @Description
 * @date 2024/9/6
 */
public class KeyUtil {
    public static void main(String[] args) throws Exception{
        // Create a key pair generator for RSA
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        // Initialize the key pair generator with a 2048-bit key size
        keyPairGenerator.initialize(1024);
        // Generate a key pair
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        // Get the private key
        PrivateKey privateKey = keyPair.getPrivate();
        // Get the public key
        PublicKey publicKey = keyPair.getPublic();
        // Encode the keys using base64
        String privateKeyEncoded = Base64.getEncoder().encodeToString(privateKey.getEncoded());
        String publicKeyEncoded = Base64.getEncoder().encodeToString(publicKey.getEncoded());
        // Print the keys
        System.out.println("Private key:\n" + privateKeyEncoded);
        System.out.println("Public key:\n" + publicKeyEncoded);
    }

}
